package com.daxia.ogmall.web.controller.m;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.daxia.ogmall.common.MyJSONObject;
import com.daxia.ogmall.dto.ProvinceDTO;
import com.daxia.ogmall.dto.api.ProvinceAPIDTO;
import com.daxia.ogmall.dto.api.info.ProvinceInfoAPIDTO;
import com.daxia.ogmall.model.City;
import com.daxia.ogmall.model.District;
import com.daxia.ogmall.support.MPage;

@Controller
@RequestMapping(value = "/m/province", produces = "application/json;charset=UTF-8")
public class MProvinceController extends MBaseController {
    
    @ResponseBody
    @RequestMapping("list")
    public String list(ProvinceDTO dto, MPage page) throws Exception {
    
        List<ProvinceDTO> provinceDTOs = provinceService.find(dto, page);

        return toApiOutput(provinceDTOs, ProvinceAPIDTO.class, ProvinceInfoAPIDTO.class, page);
    }
    
    @ResponseBody
    @RequestMapping("plist")
    public String plist() {
    	MyJSONObject data = new MyJSONObject();
    	JSONArray provinceInfos = new JSONArray();
    	List<ProvinceDTO> provinceList = provinceService.findAll();
    	for (ProvinceDTO provinceDTO : provinceList) {
    		MyJSONObject provinceInfo = new MyJSONObject();
    		MyJSONObject province = new MyJSONObject();
    		JSONArray cityInfos = new JSONArray();
    		List<City> citys = provinceDTO.getCitys();
    		
    		for (City city : citys) {
    			MyJSONObject cityInfo = new MyJSONObject();
    			cityInfo.put("cityId", city.getId());
    			cityInfo.put("cityName", city.getName());
    			
    			
    			JSONArray districtInfos = new JSONArray();
    			List<District> districts = city.getDistricts();
    			for (District district : districts) {
    				MyJSONObject districtInfo = new MyJSONObject();
    				districtInfo.put("districtId", district.getId());
    				districtInfo.put("districtName", district.getName());
    				
    				districtInfos.add(districtInfo);
    				
    			}
    			cityInfo.put("districtInfos",districtInfos);
    			cityInfos.add(cityInfo);
    		}
    		province.put("provinceId", provinceDTO.getId());
    		province.put("provinceName", provinceDTO.getName());
    		province.put("cityInfos", cityInfos);
    		provinceInfo.put(provinceDTO.getName(), province);
    		
    		provinceInfos.add(provinceInfo);
    	}
    	
    	data.put("provinceInfos", provinceInfos);
    	return toJson(data);
    }
    
}
